package controller

import (
	"net/http"
	"strconv"

	"soma-server/common"
	modelSystem "soma-server/model/system"
	"soma-server/pkg/e"
	r "soma-server/response"
	serviceSystem "soma-server/service/system"
	"soma-server/vo"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
)

type IApiController interface {
	GetApis(c *gin.Context)             // 获取接口列表
	GetApiTree(c *gin.Context)          // 获取接口树(按接口Category字段分类)
	CreateApi(c *gin.Context)           // 创建接口
	UpdateApiById(c *gin.Context)       // 更新接口
	BatchDeleteApiByIds(c *gin.Context) // 批量删除接口
}

type ApiController struct {
	ApiService serviceSystem.IApiService
}

func NewApiController() IApiController {
	apiService := serviceSystem.NewApiService()
	apiController := ApiController{ApiService: apiService}
	return apiController
}

//	@Summary		获取接口列表
//	@Description	获取接口列表
//	@Param			apiListRequest	body	vo.ApiListRequest	false	"请求参数"
//	@Tags			api
//	@Accept			json
//	@Produce		json
//	@Success		200	{object}	r.ResponseData
//	@Router			/api/api/list [post]
func (ac ApiController) GetApis(c *gin.Context) {
	var req vo.ApiListRequest
	// 参数绑定
	if err := c.ShouldBind(&req); err != nil {
		common.Log.Errorln(err.Error())
		r.Response(c, http.StatusBadRequest, e.BINDING_PARAMS, nil, false)
		return
	}
	// 参数校验
	if err := common.Validate.Struct(&req); err != nil {
		errStr := err.(validator.ValidationErrors)[0].Translate(common.Trans)
		common.Log.Errorln(errStr)
		r.Response(c, http.StatusBadRequest, e.INVALID_PARAMS, nil, false)
		return
	}
	// 获取
	apis, total, err := ac.ApiService.GetApis(&req)
	if err != nil {
		common.Log.Errorln("获取接口列表失败")
		r.Response(c, http.StatusBadRequest, e.ERROR_GET_API_LIST, nil, false)
		return
	}
	r.Response(c, http.StatusOK, e.SUCCESS_GET_API_LIST, gin.H{
		"list":    apis,
		"total":   total,
	}, true)
}

// 获取接口树(按接口Category字段分类)
func (ac ApiController) GetApiTree(c *gin.Context) {
	tree, err := ac.ApiService.GetApiTree()
	if err != nil {
		common.Log.Errorln("获取接口树失败")
		r.Response(c, http.StatusBadRequest, e.ERROR_GET_API_TREE, nil, false)
		return
	}
	r.Response(c, http.StatusOK, e.SUCCESS_GET_API_TREE, gin.H{
		"tree": tree,
	}, true)
}

// 创建接口
func (ac ApiController) CreateApi(c *gin.Context) {
	var req vo.CreateApiRequest
	// 参数绑定
	if err := c.ShouldBind(&req); err != nil {
		common.Log.Errorln(err.Error())
		r.Response(c, http.StatusBadRequest, e.BINDING_PARAMS, nil, false)
		return
	}
	// 参数校验
	if err := common.Validate.Struct(&req); err != nil {
		errStr := err.(validator.ValidationErrors)[0].Translate(common.Trans)
		common.Log.Errorln(errStr)
		r.Response(c, http.StatusBadRequest, e.INVALID_PARAMS, nil, false)
		return
	}

	// 获取当前用户
	ur := serviceSystem.NewUserService()
	ctxUser, err := ur.GetCurrentUser(c)
	if err != nil {
		common.Log.Errorln("获取当前用户信息失败")
		r.Response(c, http.StatusBadRequest, e.ERROR_GET_CURRENT_USER, nil, false)
		return
	}

	api := modelSystem.Api{
		Method:   req.Method,
		Path:     req.Path,
		Category: req.Category,
		Desc:     req.Desc,
		Creator:  ctxUser.Username,
	}

	// 创建接口
	err = ac.ApiService.CreateApi(&api)
	if err != nil {
		common.Log.Errorln("创建接口失败: " + err.Error())
		r.Response(c, http.StatusBadRequest, e.ERROR_CREATE_API_INTERFACE, nil, false)
		return
	}

	r.Response(c, http.StatusOK, e.SUCCESS_CREATE_API_INTERFACE, nil, true)
}

// 更新接口
func (ac ApiController) UpdateApiById(c *gin.Context) {
	var req vo.UpdateApiRequest
	// 参数绑定
	if err := c.ShouldBind(&req); err != nil {
		common.Log.Errorln(err.Error())
		r.Response(c, http.StatusBadRequest, e.BINDING_PARAMS, nil, false)
		return
	}
	// 参数校验
	if err := common.Validate.Struct(&req); err != nil {
		errStr := err.(validator.ValidationErrors)[0].Translate(common.Trans)
		common.Log.Errorln(errStr)
		r.Response(c, http.StatusBadRequest, e.INVALID_PARAMS, nil, false)
		return
	}

	// 获取路径中的apiId
	apiId, _ := strconv.Atoi(c.Param("apiId"))
	if apiId <= 0 {
		common.Log.Errorln("接口ID不正确")
		r.Response(c, http.StatusBadRequest, e.ERROR_API_ID_INCORRECT, nil, false)
		return
	}

	// 获取当前用户
	ur := serviceSystem.NewUserService()
	ctxUser, err := ur.GetCurrentUser(c)
	if err != nil {
		common.Log.Errorln("获取当前用户信息失败")
		r.Response(c, http.StatusBadRequest, e.ERROR_GET_CURRENT_USER, nil, false)
		return
	}

	api := modelSystem.Api{
		Method:   req.Method,
		Path:     req.Path,
		Category: req.Category,
		Desc:     req.Desc,
		Creator:  ctxUser.Username,
	}

	err = ac.ApiService.UpdateApiById(uint(apiId), &api)
	if err != nil {
		common.Log.Errorln("更新接口失败: " + err.Error())
		r.Response(c, http.StatusBadRequest, e.ERROR_UPDATE_API_INTERFACE, nil, false)
		return
	}

	r.Response(c, http.StatusOK, e.SUCCESS_UPDATE_API_INTERFACE, nil, true)
}

// 批量删除接口
func (ac ApiController) BatchDeleteApiByIds(c *gin.Context) {
	var req vo.DeleteApiRequest
	// 参数绑定
	if err := c.ShouldBind(&req); err != nil {
		common.Log.Errorln(err.Error())
		r.Response(c, http.StatusBadRequest, e.BINDING_PARAMS, nil, false)
		return
	}
	// 参数校验
	if err := common.Validate.Struct(&req); err != nil {
		errStr := err.(validator.ValidationErrors)[0].Translate(common.Trans)
		common.Log.Errorln(errStr)
		r.Response(c, http.StatusBadRequest, e.INVALID_PARAMS, nil, false)
		return
	}

	// 删除接口
	err := ac.ApiService.BatchDeleteApiByIds(req.ApiIds)
	if err != nil {
		common.Log.Errorln("删除接口失败: " + err.Error())
		r.Response(c, http.StatusBadRequest, e.ERROR_DELETE_API_INTERFACE, nil, false)
		return
	}

	r.Response(c, http.StatusOK, e.SUCCESS_DELETE_API_INTERFACE, nil, true)
}
